package com.wl.java_spring_boot01.modules.account.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wl.java_spring_boot01.modules.account.dao.RoleDao;
import com.wl.java_spring_boot01.modules.account.dao.UserRoleDao;
import com.wl.java_spring_boot01.modules.account.entity.Role;
import com.wl.java_spring_boot01.modules.account.service.RoleService;
import com.wl.java_spring_boot01.modules.common.vo.Result;
import com.wl.java_spring_boot01.modules.common.vo.SearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @author 汪林
 * @date 2020/8/22 17:49
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private UserRoleDao userRoleDao;

    //查询所有
    @Override
    public List<Role> getRoles() {
        return Optional.ofNullable(roleDao.getRoles())
                .orElse(Collections.emptyList());
    }

    //分页
    @Override
    public PageInfo<Role> getUsersBySearchVo(SearchVo searchVo) {
        searchVo.initSearchVo();
        PageHelper.startPage(searchVo.getCurrentPage(),searchVo.getPageSize());
        return new PageInfo<Role>(
                Optional.ofNullable(roleDao.getUsersBySearchVo(searchVo))
                        .orElse(Collections.emptyList()));
    }

    //增加
    @Override
    public Result<Role> insertRole(Role role) {
        //1.判断增加的角色是否存在
        Role roleTemp = roleDao.getRoleByRoleName(role.getRoleName());
        if (roleTemp != null) {
            return new Result<Role>(
                    Result.ResultStatus.FAILD.status, "Role name is repeat.");
        }
        //2.插入数据
        roleDao.insertRole(role);
        return new Result<>(Result.ResultStatus.SUCCESS.status,"insert success",role);
    }

    //id查找
    @Override
    public Role getRoleByRoleId(int roleId) {
        return roleDao.getRoleByRoleId(roleId);
    }

    //修改
    @Override
    public Result<Role> updateRole(Role role) {
        //判断修改的角色名是否重复
        Role roleTemp = roleDao.getRoleByRoleName(role.getRoleName());
        if (roleTemp != null) {
            return new Result<Role>(
                    Result.ResultStatus.FAILD.status, "Role name is repeat.");
        }
        roleDao.updateRole(role);
        return new Result<>(Result.ResultStatus.SUCCESS.status,"update success",role);
    }

    @Override
    public Result<Object> deleteRole(int roleId) {
        roleDao.deleteUser(roleId);
        userRoleDao.deleteUserRoleByRoleId(roleId);
        return new Result<Object>(Result.ResultStatus.SUCCESS.status,"delete success.");
    }
}
